#include "userregistration.h"

UserRegistration::UserRegistration(QWidget *parent)
    : QWidget(parent)
{
    if (!set.loadSettings())
        QMessageBox::information(this, QString::fromLocal8Bit("Помилка файла конфігурації"),
                                       QString::fromLocal8Bit("Синтаксична помилка у файлі конфігурації.\n"
                                                              "Програма буде налаштована за замовчуванням!"));
    user_inicial = new LineEdit(this);
    connect(user_inicial, SIGNAL(textChanged(QString)), SLOT(inputingText(QString)));
    house_number = new LineEdit(this);
    connect(house_number, SIGNAL(textChanged(QString)), SLOT(inputingText(QString)));
    home_phone = new LineEdit(this);
    connect(home_phone, SIGNAL(textChanged(QString)), SLOT(inputingText(QString)));
    mobile_phone = new LineEdit(this);
    connect(mobile_phone, SIGNAL(textChanged(QString)), SLOT(inputingText(QString)));
    begin_service_date = new LineEdit(this);
    begin_service_date->setText(__getDateForDatabaseEntry());
    connect(begin_service_date, SIGNAL(textChanged(QString)), SLOT(inputingText(QString)));
    notation = new QTextEdit(this);
    login = new LineEdit(this);
    login->setText(__getRandomText(Login));
    connect(login, SIGNAL(textChanged(QString)), SLOT(inputingText(QString)));
    password = new LineEdit(this);
    password->setText(__getRandomText(Password));
    connect(password, SIGNAL(textChanged(QString)), SLOT(inputingText(QString)));
    street_name = new QComboBox(this);
    service_type = new QComboBox(this);
    client_machine = new QComboBox(this);
    sector_building = new QComboBox(this);
    switchport_number = new QComboBox(this);
    connection_type = new QComboBox(this);
    __configureProgram();
    add_but = new PushButton(this);
    add_but->setToolTip(QString::fromLocal8Bit("Додати користувача"));
    QPixmap pix_for_add_but("icons/plus_grey.png");
    add_but->setFixedSize(pix_for_add_but.size());
    add_but->setIcon(QIcon(pix_for_add_but));
    add_but->setIconSize(add_but->size());
    add_but->setEnabled(false);
    connect(add_but, SIGNAL(clicked()), SLOT(addUser()));
    QGridLayout *grid_layout = new QGridLayout(this);
    QLabel *user_inicial_label = new QLabel(QString::fromLocal8Bit("ПІП (через пробіл):"), this);
    grid_layout->addWidget(user_inicial_label, 0, 0);
    grid_layout->addWidget(user_inicial, 0, 1);
    QLabel *street_name_lab = new QLabel(QString::fromLocal8Bit("вулиця:"), this);
    grid_layout->addWidget(street_name_lab, 1, 0);
    grid_layout->addWidget(street_name, 1, 1);
    QLabel *house_number_lab = new QLabel(QString::fromLocal8Bit("номер будинку/квартири:"));
    grid_layout->addWidget(house_number_lab, 2, 0);
    grid_layout->addWidget(house_number, 2, 1);
    QLabel *sector_building_lab = new QLabel(QString::fromLocal8Bit("номер під'їзду:"), this);
    grid_layout->addWidget(sector_building_lab, 3, 0);
    grid_layout->addWidget(sector_building, 3, 1);
    QLabel *home_phone_lab = new QLabel(QString::fromLocal8Bit("домашній телефон:"), this);
    grid_layout->addWidget(home_phone_lab, 4, 0);
    grid_layout->addWidget(home_phone, 4, 1);
    QLabel *mobile_phone_lab = new QLabel(QString::fromLocal8Bit("мобільний телефон:"), this);
    grid_layout->addWidget(mobile_phone_lab, 5, 0);
    grid_layout->addWidget(mobile_phone, 5, 1);
    QLabel *service_type_lab = new QLabel(QString::fromLocal8Bit("тип сервісу:"), this);
    grid_layout->addWidget(service_type_lab, 6, 0);
    grid_layout->addWidget(service_type, 6, 1);
    QLabel  *connection_type_lab = new QLabel(QString::fromLocal8Bit("тип підключення:"), this);
    grid_layout->addWidget(connection_type_lab, 7, 0);
    grid_layout->addWidget(connection_type, 7, 1);
    QLabel *client_machine_lab = new QLabel(QString::fromLocal8Bit("тип обладнання:"), this);
    grid_layout->addWidget(client_machine_lab, 8, 0);
    grid_layout->addWidget(client_machine, 8, 1);
    QLabel *switchport_number_lab = new QLabel(QString::fromLocal8Bit("номер порта:"), this);
    grid_layout->addWidget(switchport_number_lab, 9, 0);
    grid_layout->addWidget(switchport_number, 9, 1);
    QLabel *begin_service_date_lab = new QLabel(QString::fromLocal8Bit("дата підключення (р-м-д):"), this);
    grid_layout->addWidget(begin_service_date_lab, 10, 0);
    grid_layout->addWidget(begin_service_date, 10, 1);
    QLabel *login_lab = new QLabel(QString::fromLocal8Bit("логін:"), this);
    grid_layout->addWidget(login_lab, 11, 0);
    grid_layout->addWidget(login, 11, 1);
    QPixmap pix("icons/refresh(1).png");
    new_login_but = new PushButton(this);
    new_login_but->setToolTip(QString::fromLocal8Bit("Новий логін"));
    new_login_but->setFixedSize(pix.size());
    new_login_but->setIcon(pix);
    new_login_but->setIconSize(new_login_but->size());
    new_login_but->setFlat(true);
    connect(new_login_but, SIGNAL(clicked()), SLOT(setNewLogin()));
    grid_layout->addWidget(new_login_but, 11, 2);
    QLabel *password_lab = new QLabel(QString::fromLocal8Bit("пароль:"), this);
    grid_layout->addWidget(password_lab, 12, 0);
    grid_layout->addWidget(password, 12, 1);
    new_passw_but = new PushButton(this);
    new_passw_but->setToolTip(QString::fromLocal8Bit("Новий пароль"));
    new_passw_but->setFixedSize(pix.size());
    new_passw_but->setIcon(pix);
    new_passw_but->setIconSize(new_passw_but->size());
    new_passw_but->setFlat(true);
    connect(new_passw_but, SIGNAL(clicked()), SLOT(setNewPassw()));
    grid_layout->addWidget(new_passw_but, 12, 2);
    QLabel *notation_lab = new QLabel(QString::fromLocal8Bit("примітка:"), this);
    grid_layout->addWidget(notation_lab, 13, 0);
    grid_layout->addWidget(notation, 13, 1);
    grid_layout->addWidget(add_but, 14, 0);
    setLayout(grid_layout);
    __getDateForDatabaseEntry();
}

void UserRegistration::setNewLogin()
{
    login->setText(__getRandomText(Login));
}

void UserRegistration::setNewPassw()
{
    password->setText(__getRandomText(Password));
}

void UserRegistration::__configureProgram()
{
    street_name->addItems(set.getSectionsData()["streets"]);
    service_type->addItems(set.getSectionsData()["tos"]);
    client_machine->addItems(set.getSectionsData()["user_device_type"]);
    connection_type->addItems(set.getSectionsData()["connection_type"]);
    const QStringList &s_l = set.getSectionsData()["sec_build_num"];
    int num = atoi(s_l[s_l.size() - 1].toAscii());
    for (int i = 1; i <= num; i++) sector_building->addItem(QString().setNum(i));
    const QStringList &s_p = set.getSectionsData()["port_num"];
    num = atoi(s_p[s_p.size() - 1].toAscii());
    for(int i = 1; i <= num; i++) switchport_number->addItem(QString().setNum(i));
}

QString UserRegistration::__getRandomText(RandomType login_type)
{
    QTime time = QTime::currentTime();
    QDate date = QDate::currentDate();
    unsigned int exclusive = date.year() + date.month() + date.day() + time.hour() + time.minute() + time.second() + time.msec() + login_type;
    unsigned short string_size = (exclusive % 8) + 8; // розмір пароля та логіна - від 8 до 15 символів
    unsigned short start = 93 - string_size;
    QString random_text;
    short t;
    for (int i = 0; i < string_size; i++) {
        t = ((exclusive % (start + i)) + 33); // отримуємо символи ASCII в діапазоні від 33 до 126
        if (!isdigit(t) && !isalpha(t)) // в паролі містяться тільки числа та літери
        {
            if (t < 48) t += 48 - t + (exclusive % 10);
            else if (t < 65) t += 65 - t + (exclusive % 25);
            else if (t < 97) t += 97 - t + (exclusive % 25);
        }
        random_text[i] = (char)t;
    }
    return random_text;
}

QString UserRegistration::__getDateForDatabaseEntry()
{
    QString date, t;
    date.setNum(QDate::currentDate().year());
    date += "-";
    t.setNum(QDate::currentDate().month());
    date += t;
    date += "-";
    t.setNum(QDate::currentDate().day());
    date += t;
    return date;
}

void UserRegistration::addUser()
{
    QSqlQuery query;
    QString user_login = login->text();
    QString u_inicial = user_inicial->text();
    QString str_query = "select inicial from clients where inicial='%1';";
    str_query = str_query.arg(u_inicial);
    if (!query.exec(str_query))
    {
        QMessageBox::critical(this, "Error...", QString::fromLocal8Bit("Помилка читання бази даних!"), "Ok");
        return;
    }
    if (query.next())
    {
        //QSqlRecord rec = query.record();
       /* if (query.value(rec.indexOf("login")).toString() == user_login)
        {
            QMessageBox::critical(this, "Error...", QString::fromLocal8Bit("Користувач з таким логіном вже існує.\n"
                                                                           "Новий логін згенерується автоматично!"), "Ok");
            login->setText(__getRandomText(Login));
            return;
        }*/
        QString msg = QString::fromLocal8Bit("Користувач %1 вже знаходиться в базі даних!");
        msg = msg.arg(u_inicial);
        QMessageBox::critical(this, "Error...", msg, "Ok");
        return;
    }
    str_query = "insert into radcheck(username, attribute, value, op) values ('%1', \"ClearText-Password\", '%2', \":=\")";
    str_query = str_query.arg(user_login).arg(password->text());
    if (!query.exec(str_query))
    {
        QMessageBox::critical(this, "Error...", QString::fromLocal8Bit("Помилка запису в базу даних!"), "Ok");
        return;
    }
    str_query = "select id from radcheck where UserName = '%1' order by id desc;"; // дізнаємось id добавленого клієнта в таблиці radcheck
    str_query = str_query.arg(user_login);
    if (!query.exec(str_query))
    {
        QMessageBox::critical(this, "Error...", QString::fromLocal8Bit("Помилка запису в базу даних!"), "Ok");
        return;
    }
    QSqlRecord record = query.record();
    uint client_id_in_radcheck_table;
    query.next();
    client_id_in_radcheck_table = query.value(record.indexOf("id")).toInt();
    str_query = "insert into clients(id, inicial, street, address, sector_bulding, home_phone, mobile_phone, service_type, type_machine, "
            "port_number, begin_service, notation) values(%1, '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10', '%11', '%12');";
    str_query = str_query.arg(client_id_in_radcheck_table).arg(u_inicial).arg(street_name->currentText())
            .arg(house_number->text()).arg(sector_building->currentText()).arg(home_phone->text()).arg(mobile_phone->text())
            .arg(service_type->currentText()).arg(client_machine->currentText()).arg(switchport_number->currentText())
            .arg(begin_service_date->text()).arg(notation->toPlainText());
    if (!query.exec(str_query))
    {
        QMessageBox::critical(this, "Error...", QString::fromLocal8Bit("Помилка запису в базу даних!"), "Ok");
        return;
    }
    user_inicial->clear();
    house_number->clear();
    home_phone->clear();
    mobile_phone->clear();
    begin_service_date->setText(__getDateForDatabaseEntry());
    notation->clear();
    login->setText(__getRandomText(Login));
    password->setText(__getRandomText(Password));
    QMessageBox::information(this, "Success", QString::fromLocal8Bit("Клієнт успішно добавлений в базу даних"), "Ok");
}

void UserRegistration::close()
{
    user_inicial->clear();
    house_number->clear();
    home_phone->clear();
    mobile_phone->clear();
    begin_service_date->setText(__getDateForDatabaseEntry());
    notation->clear();
    login->setText(__getRandomText(Login));
    password->setText(__getRandomText(Password));
    hide();
}

void UserRegistration::inputingText(QString)
{
    add_but->setFlat(true);
    if (user_inicial->text().isEmpty() || house_number->text().isEmpty() || begin_service_date->text().isEmpty() ||
            login->text().isEmpty() || password->text().isEmpty())
    {
        add_but->setEnabled(false);
        return;
    }
    if (home_phone->text().isEmpty() && mobile_phone->text().isEmpty())
    {
        add_but->setEnabled(false);
        return;
    }
    add_but->setEnabled(true);
}
